#include "TcpServer.hpp"
#include <memory>
#include "Translate.hpp"
#include <algorithm>
#include <cctype>   //toupper
#include "daemon.hpp"

Translate trans;
void Usage(const std::string &proc)
{
    std::cout << "格式：" << proc << " port" << std::endl;
}
void Ping(int sockfd, const InetAddr &addr)
{
    char buffer[128];
    int n = read(sockfd, buffer, sizeof buffer - 1);
    if (n > 0)
    { 
        buffer[n] = 0;
        std::string str = addr.PrintDebug();
        str += buffer;  
        std::cout << str << std::endl;
        write(sockfd, str.c_str(), str.size());
    }
    else if (n == 0)
        lg.LogMessage(Warning, "client closed\n");
    else
        lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
}
void Translate(int sockfd, const InetAddr &addr)
{
    char buffer[64];
    int n = read(sockfd, buffer, sizeof buffer - 1);
    if (n > 0)
    { 
        buffer[n] = 0;
        std::string tansword = trans.GetChinese(buffer);
        write(sockfd, tansword.c_str(), tansword.size());
    }
    else if (n == 0)
        lg.LogMessage(Warning, "client closed\n");
    else
        lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
}
void Transform(int sockfd, const InetAddr &addr)
{
    char buffer[64];
    int n = read(sockfd, buffer, sizeof buffer - 1);
    if (n > 0)
    { 
        buffer[n] = 0;
        std::string str = buffer;
        transform(str.begin(), str.end(), str.begin(), [](char c){ return toupper(c);});
        write(sockfd, str.c_str(), str.size());
    }
    else if (n == 0)
        lg.LogMessage(Warning, "client closed\n");
    else
        lg.LogMessage(Error, "读错误, errno:%d, %s\n", errno, strerror(errno));
}
void Default(int sockfd, const InetAddr &addr)
{
    std::cout << "没有此功能, 或者client 退出" << std::endl; 
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[1]);
        return usage_err;
    }
    lg.Enable(ClassFile);   //这个一定要放在tsvr前面，Init就有日志
    // Daemon(false, true); //

    std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>(std::stoi(argv[1]));

    // Daemon(false, true);

    tsvr->Init();
    Daemon(false, false); //这里有问题
    tsvr->Register("ping", Ping);
    tsvr->Register("translate", Translate);

    tsvr->Register("transform", Transform);
    tsvr->Register("default", Default);
    
    // lg.Enable(ClassFile);
    tsvr->Start();

    return 0;
}